﻿using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MyExtension.Redis
{
    public class RedisBasketRepository : IRedisBasketRepository
    {
        private readonly ILogger<RedisBasketRepository> _logger;
        private readonly ConnectionMultiplexer _redis;
        private readonly IDatabase _database;
        public RedisBasketRepository(ILogger<RedisBasketRepository>logger,ConnectionMultiplexer redis)
        {
            _logger = logger;
            _redis = redis;
            _database = _redis.GetDatabase();
        }

        private IServer GetServer() { 
            var endPoints = _redis.GetEndPoints();
            return _redis.GetServer(endPoints.First());
        }
        public async Task Clear()
        {
            foreach (var item in _redis.GetEndPoints())
            {
                var server = GetServer();
                foreach (var key in server.Keys())
                {
                    await _database.KeyDeleteAsync(key);
                }
            }
        }

        public Task<bool> Exists(string key)
        {
            return _database.KeyExistsAsync(key);
        }

        public async Task<TEntity> Get<TEntity>(string key)
        {
            var value = await _database.StringGetAsync(key);
            if (value.HasValue)
            {
                var jsonString = Encoding.UTF8.GetString(value!);

                return JsonConvert.DeserializeObject<TEntity>(jsonString)!;
            }
            else
            {
                return default(TEntity)!;
            }
        }

        public async Task<string> GetValue(string key)
        {
            return await _database.StringGetAsync(key);
        }

        public async Task Remove(string key)
        {
            await _database.KeyDeleteAsync(key);
        }

        public async Task Set(string key, object value, TimeSpan cacheTime)
        {
            if (value != null)
            {
                if(value is string cacheValue)
                {
                    await _database.StringSetAsync(key, cacheValue,cacheTime);
                }
                else
                {
                    var jsonStr = JsonConvert.SerializeObject(value);
                    var v = Encoding.UTF8.GetBytes(jsonStr);
                    await _database.StringSetAsync(key, v,cacheTime);
                }
            }
        }
    }
}
